package com.haoshuang.zhouzhoubang.ui.activity


import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.constraintlayout.motion.widget.Debug.getLocation
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.ThreadUtils
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityServiceOrderStatusBinding
import com.haoshuang.zhouzhoubang.model.bean.Image2Bean
import com.haoshuang.zhouzhoubang.model.bean.OrderDetail2Bean
import com.haoshuang.zhouzhoubang.model.bean.PriceBean
import com.haoshuang.zhouzhoubang.model.bean.TimeBean8
import com.haoshuang.zhouzhoubang.model.event.OrderStatusChangeEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshMasterOrderEvent
import com.haoshuang.zhouzhoubang.model.event.ShouKuanPaySuccessEvent
import com.haoshuang.zhouzhoubang.model.event.SignSuccessEvent
import com.haoshuang.zhouzhoubang.model.event.TransferOrderSuccess
import com.haoshuang.zhouzhoubang.ui.adapter.ChooseImageAdapter2
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter23
import com.haoshuang.zhouzhoubang.ui.adapter.ServiceOrderMemberListAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.CheckDialog
import com.haoshuang.zhouzhoubang.ui.dialog.CheckDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.OrderDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowOrderPriceDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowRewardNoticeDialog
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog3
import com.haoshuang.zhouzhoubang.ui.dialog.TimelDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tis2Dialog
import com.haoshuang.zhouzhoubang.ui.dialog.YsDialog
import com.haoshuang.zhouzhoubang.ui.page.order.assignment.TaskAssignmentActivity
import com.haoshuang.zhouzhoubang.ui.page.order.contact.ContactWorkerActivity
import com.haoshuang.zhouzhoubang.ui.page.order.receiveorder.detail.ServiceItemAdapter
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.haoshuang.zhouzhoubang.ui.page.order.upload.UploadInServiceActivity
import com.haoshuang.zhouzhoubang.ui.vm.ServiceOrderStatusViewModel
import com.haoshuang.zhouzhoubang.utils.GlideEngine
import com.haoshuang.zhouzhoubang.utils.LocationUtils
import com.haoshuang.zhouzhoubang.utils.NavigationUtils
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.haoshuang.zhouzhoubang.utils.oss.OSSUtils
import com.haoshuang.zhouzhoubang.utils.oss.ProgressCallback2
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.ktx.copyToClipboard
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.isBold
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

/**
 *  服务订单详情
 */
class ServiceOrderStatusActivity :
    BaseVMActivity<ServiceOrderStatusViewModel, ActivityServiceOrderStatusBinding>() {
    private var countDownTimer: CountDownTimer? = null
    private var detailBean: OrderDetail2Bean? = null

    // 选中的队员列表集合
    private val imageList = arrayListOf<OrderDetail2Bean.TeamMember>()

    /*队员列表适配器*/
    private lateinit var adapter: ServiceOrderMemberListAdapter
    lateinit var imageadapter: ImageAdapter23
    var list = arrayListOf<Image2Bean>()
    var str = ""

    // 是不是返工订单
    private var is_rework = false

    /**
     * 确认上门
     */
    fun confirmLocation() {
        PermissionHelper.requestPermission(
            this,
            "定位权限使用说明",
            "用于服务确认上门, 获取当前位置",
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) {
            if (it) {
                showLoading("定位中...")
                getLocation()
            } else {
                XPopup.Builder(this@ServiceOrderStatusActivity)
                    .asCustom(
                        Tis2Dialog(
                            this@ServiceOrderStatusActivity,
                            "开启定位权限是为了获取您当前位置"
                        ) {
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data = Uri.parse("package:" + getPackageName())
                            startActivity(intent)

                        })
                    .show()
            }
        }
    }

    var type1 = 0
    var isqd = 0
    var order_id = ""
    override fun initView(savedInstanceState: Bundle?) {
        is_rework = intent.getBooleanExtra("is_rework", false)
        imageadapter = ImageAdapter23(list)
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            llRewardView.clickWithTrigger {
                XPopup.Builder(this@ServiceOrderStatusActivity)
                    .asCustom(ShowRewardNoticeDialog(this@ServiceOrderStatusActivity))
                    .show()
            }
            blZb.clickWithTrigger {
                startPage<WarrantyActivity>("ids" to ids)
            }
            tvLeftButton3.clickWithTrigger {
                // 收款
                startPage<ShouKuanActivity>(
                    "team_id" to order_id,
                    "serviceName" to detailBean?.store_name
                )
            }

            llBj2.clickWithTrigger {
                // 验收码
                vm.getData222("id" to ids)

            }
            binding.tvRightButton2.clickWithTrigger {
                // 立即签到
                if (isqd == 0) {
                    if (lat9.isNullOrBlank()) {
                        type1 = 1
                        signLocation()
                    } else {
                        vm.getData66("id" to ids, "lat" to lat9, "lng" to lng9)
                    }
                }

            }
            useAddress.isBold = true
            serviceTime.isBold = true
            textView54.isBold = true
            storeName.isBold = true
            rvList9.layoutManager = GridLayoutManager(this@ServiceOrderStatusActivity, 4)
            rvList9.adapter = imageadapter
            imageadapter.setOnItemClick { view, position,_ ->
                var list2 = arrayListOf<String>()

                if (list[position].isVideo == 0) {
                    list2.add(list[position].image)
                    startPage<LookActivity>("imgBeen" to list2, "position" to 0)
                } else {
                    startPage<VideoActivity>("url" to list[position].image)
                }
            }

            appBar.ivBack.setImageResource(R.mipmap.back_icon)
            appBar.tvTitle.setTextColor(resources.getColor(R.color.white))
//            str = intent.getStringExtra("str").toString()
//            appBar.tvTitle.text = str

            // 额外费用介绍
            tvEWai.clickWithTrigger {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "额外费用",
                            content = "请根据客户协商实际情况\n" +
                                    "增加额外费用，严禁恶意增价",
                            cancelStr = "",
                            confirmStr = "我知道了",
                            isHideCancel = true,
                            onCancel = {},
                            onConfirm = {})
                    )
                    .show()
            }

            // 二次上门介绍
            tvAgain.clickWithTrigger {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "二次上门",
                            content = "遇到突发状况，请与客户协商后\n提交二次上门时间。",
                            cancelStr = "",
                            confirmStr = "我知道了",
                            isHideCancel = true,
                            onCancel = {},
                            onConfirm = {})
                    )
                    .show()
            }

            // 申请二次上门
            tvAgainInputReason.clickWithTrigger {
                startPageForResult<AgainDoorInActivity>(
                    "second_visit_amount" to detailBean?.second_visit_amount,
                    "cate_id" to cate_id, "order_id" to ids.toString()
                ) { code, data ->
                    if (code == 200) {
                        vm.getData("id" to ids, "lat" to lat9, "lng" to lng9)
                    } else if (code == 201) {
                        startPageForResult<ExtraCostsPayActivity>(
                            "orderId" to detailBean?.id.toString(),
                            "payName" to "二次上门"
                        ) { code, data ->
                            vm.getData("id" to ids, "lat" to lat9, "lng" to lng9)
                        }
                    }
                }
            }
        }
    }

    private fun getLocation() {
        LocationUtils.register(this, 10000, 0, object : LocationUtils.OnLocationChangeListener {
            override fun getLastKnownLocation(location: Location?) {
                Log.e("xyh", "onLocationChanged: " + location?.latitude)
            }

            override fun onLocationChanged(location: Location?) {
                lat9 = location?.latitude.toString()
                lng9 = (location?.longitude.toString())
                when (type1) {

                    0 -> {
                        // 确认上门
                        vm.getData6("id" to ids, "lat" to lat9, "lng" to lng9)
                    }

                    1 -> {
                        // 签到
                        vm.getData66("id" to ids, "lat" to lat9, "lng" to lng9)
                    }

                    else -> {
                        vm.getData(
                            "id" to ids, "lat" to lat9, "lng" to lng9
                        )
                    }
                }
                LocationUtils.unregister()
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {

            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        LocationUtils.unregister()
    }


    var lat9 = ""
    var lng9 = ""

    fun signLocation() {
        PermissionHelper.requestPermission(
            this,
            "定位权限使用说明",
            "用于您上门签到, 获取当前位置",
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) {
            if (it) {
                showLoading("定位中...")
                getLocation()
            } else {
                XPopup.Builder(this@ServiceOrderStatusActivity)
                    .asCustom(
                        Tis2Dialog(
                            this@ServiceOrderStatusActivity,
                            "开启定位权限是为了获取您当前位置"
                        ) {
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data = Uri.parse("package:" + getPackageName())
                            startActivity(intent)

                        })
                    .show()
            }
        }
    }


    //队员添加事件
    private fun add() {
        if (user_status == 1) {
            startPageForResult<TaskAssignmentActivity>(
                "ids" to ids.toString(),
                "is_rework" to is_rework,
                "isPersonal" to (detailBean?.is_team != "1")
            ) { code, data ->
                if (code == 200) {
                    setResult(200)
                    finish()
                }
            }
        } else {
            toast("只有团长才能指派人员")
        }
    }

    //联系队员
    private fun contact(position: Int) {
        var phone = imageList[position].phone
        if (phone.isNullOrBlank()) {
            toast("电话不能为空")
        }

        callPhone(phone)
    }

    //队员头像点击
    private fun itemClick(position: Int, list: MutableList<OrderDetail2Bean.TeamMember>) {
        startPage<PersonalHomeActivity>("user_id" to list[position].user_id)
    }

    var ids = 0
    var cost_status = 0
    var is_confirm = 0
    var is_team = 0
    var json = ""
    override fun onResume() {
        super.onResume()
        vm.getData(
            "id" to ids, "lat" to lat9, "lng" to lng9
        )
    }

    var adapter8: ImageAdapter23? = null
    private val imageListInService = arrayListOf<LocalMedia>()
    var list8 = arrayListOf<Image2Bean>()
    private lateinit var inServiceAdapter: ChooseImageAdapter2

    //图片点击
    private fun itemClick2(position: Int, list: MutableList<LocalMedia>) {
        if (list[position].mimeType.contains("video")) {
            startPage<VideoActivity>("url" to imageListInService[position].realPath)
        } else {
            var list2 = arrayListOf<String>()
            list2.add(imageListInService[position].realPath)
            startPage<LookActivity>("imgBeen" to list2, "position" to 0)
        }
    }

    override fun initData() {
        ids = intent.getIntExtra("ids", 0)
        vm.getData29("id" to ids)

        vm.getData55("id" to ids)
        binding.llJe.clickWithTrigger {
            if (detailBean != null) {
                val teamPrice = detailBean!!.team_price?.team_price
                val teamLeaderPrice = detailBean!!.team_price?.team_leader_price
                val teamMemberPrice = detailBean!!.team_price?.team_member_price
                val minePrice = detailBean!!.team_price?.self_price
                XPopup.Builder(mActivity)
                    .asCustom(
                        ShowOrderPriceDialog(
                            context = mActivity,
                            prepayments_amount = detailBean!!.prepayments_amount.toString(),
                            nightPrice = "${detailBean!!.nighttime_amount}",
                            totalPrice = detailBean!!.pay_price,
                            teamPrice = teamPrice ?: "",
                            teamLeaderPrice = teamLeaderPrice ?: "",
                            teamMemberPrice = teamMemberPrice ?: detailBean!!.pay_price,
                            minePrice = minePrice ?: detailBean!!.pay_price,
                        )
                    )
                    .show()
            }
//            XPopup.Builder(this@ServiceOrderStatusActivity)
//                .asCustom(
//                    OrderDialog(
//                        this@ServiceOrderStatusActivity,
//                        str1,
//                        str2,
//                        detailBean?.paid
//                    ) {
//
//                    })
//                .show()
        }
        binding.tvComfirmDoorIn.setOnClickListener {
            // 点击确认上门
            if (is_confirm == 0) {
                if (is_team == 0) {
                    startPage<AppointmentCustomerActivity>("ids" to ids)
                } else {
                    startPage<AppointmentCustomerActivity2>("ids" to ids)
                }
            } else {
                var num = 0
                for (b in imageList) {
                    if (b.team_is_sign == "1") {
                        num += 1
                    }
                }
                if (num == imageList.size) {
                    if (lat9.isNullOrBlank()) {
                        type1 = 0
                        confirmLocation()
                    } else {
                        vm.getData6("id" to ids, "lat" to lat9, "lng" to lng9)
                    }
                } else {
                    XPopup.Builder(this@ServiceOrderStatusActivity)
                        .asCustom(
                            SmDialog(
                                this@ServiceOrderStatusActivity,
                                "当前还有${imageList.size - num}名队员未签到，请联系当事人签到！"
                            ) {

                            })
                        .show()
                }
            }

        }
        binding.tvConfirmedService.clickWithTrigger {
            // 上门中  确认服务
            startPageForResult<ComfirmDoorInActivity>(
                "ids" to ids.toInt(),
                "is_rework" to is_rework
            ) { code, data ->
                if (code == 200) {
                    finish()
                }
            }
        }
        type1 = 3
        binding.apply {
            inServiceAdapter = ChooseImageAdapter2(
                this@ServiceOrderStatusActivity,
                10,
                imageListInService,
                ::addInService,
                ::deleteInService,
                ::itemClick2
            )
            rvInService.layoutManager = GridLayoutManager(this@ServiceOrderStatusActivity, 4)
            rvInService.adapter = inServiceAdapter
            /*  inServiceAdapter?.setOnItemClick { view, position ->

              }*/
            adapter8 = ImageAdapter23(list8)
            rvInService1.layoutManager = GridLayoutManager(this@ServiceOrderStatusActivity, 4)
            rvInService1.adapter = adapter8
            adapter8?.setOnItemClick { view, position,_ ->
                if (list8[position].isVideo == 0) {
                    var list2 = arrayListOf<String>()
                    list2.add(list8[position].image)
                    startPage<LookActivity>("imgBeen" to list2, "position" to 0)
                } else {
                    startPage<VideoActivity>("url" to list8[position].image)
                }
            }
            tvMore.clickWithTrigger {
                llGd.visible()
                tvMore.gone()
            }
            tvMore2.clickWithTrigger {
                llGd.gone()
                tvMore.visible()
            }
        }
        binding.btnSubmitAcceptance.clickWithTrigger {
            // 提交验收
            vm.getData0("order_id" to ids)

        }
        binding.tvFw.clickWithTrigger {
            startPage<ServiceLogActivity>("ids" to ids)
        }
        binding.tvEWaiAppendPrice.clickWithTrigger {
            // 追加费用
            SetExtraCostsActivity.launch(mActivity, ids, 1)
//            if (list55.size > 0) {
//                startPage<ExtraCostsSelectActivity>("ids" to ids, "type" to 1)
//            } else {
//                startPage<ExtraCostsActivity>("ids" to ids, "type" to 1)
//            }
        }
        binding.btB2.clickWithTrigger {
            startPage<TaskAssignmentActivity>("ids" to ids.toString(), "is_rework" to is_rework, "isPersonal" to (detailBean?.is_team != "1"))
        }
        binding.llKf.clickWithTrigger {
            // 打电话给客服
            if (store_order_tel.isNullOrBlank()) {
                toast("电话不能为空")
            }

            var intent = Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:${store_order_tel}"));
            startActivity(intent)
        }
        binding.llBj.clickWithTrigger {
            // 报警
            if (store_order_alarm_tel.isNullOrBlank()) {
                toast("电话不能为空")
            }
            var intent = Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:${store_order_alarm_tel}"));
            startActivity(intent)
        }
        binding.imageView21.clickWithTrigger {
            // 打电话给客户
            if (user_phone.isNullOrBlank()) {
                toast("电话不能为空")
            }
            callPhone(user_phone)
            /*  var intent =  Intent(Intent.ACTION_DIAL);
              intent.setData(Uri.parse("tel:${user_phone}"));
              startActivity(intent)*/
        }
        binding.ivDw.clickWithTrigger {
            // 点击定位
            if (lat.isNullOrBlank()) {
                toast("经纬度不能为空")
                return@clickWithTrigger
            }
            NavigationUtils.startNavigation(
                mActivity,
                lat,
                lng,
                user_address
            )
        }
        binding.useAddress.clickWithTrigger {
            // 复制地址
            copyToClipboard(user_address)
            toast("服务地址复制成功")
        }
        binding.btB1.clickWithTrigger {
            // 修改上门时间
            startPageForResult<UpdateServiceTimeActivity>("cate_id" to cate_id){code, data ->
                if (code == Activity.RESULT_OK){
                    if (data != null) {
                        val service_day = data.getStringExtra("service_day").toString()
                        val service_day1 = data.getStringExtra("service_day1")
                        val service_time = data.getStringExtra("service_time").toString()
                        vm.getData3(
                            "order_id" to ids,
                            "service_day" to service_day,
                            "service_time" to service_time
                        )
                    }
                }
            }
        }
        binding.btnSubmitAcceptance22.clickWithTrigger {
            // 处理退款
            startPage<ReturnDetailActivity>("ids" to ids)
        }
        binding.btnSubmitAcceptance2.clickWithTrigger {
            if (AccountUtils.canReminderUserAcceptanceTime(ids.toString())){
                vm.getData22("id" to ids)
            }else{
                XPopup.Builder(mActivity)
                    .asCustom(ConfirmDialog(
                        context =mActivity,
                        title = "温馨提示",
                        content = "5分钟内只能提醒一次, 请稍后再试",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        isHideAgain = false,
                        onCancel = {},
                        onConfirm = {}))
                    .show()
            }
            // 提醒验收

        }

        // 联系师傅
        binding.tvContactWorker.clickWithTrigger {
            startPage<ContactWorkerActivity>("order_id" to ids.toString())
        }
    }

    //删除第几张图片
    private fun deleteInService(position: Int) {
        deleteImage(
            position,
            imageListInService,
            inServiceAdapter
        )
    }

    /**删除图片的抽象方法*/
    private fun deleteImage(
        position: Int,
        imageList: ArrayList<LocalMedia>,
        adapter: ChooseImageAdapter2
    ) {
        imageList.removeAt(position)
        adapter.notifyDataSetChanged()
    }

    private fun setUrl(result: ArrayList<LocalMedia>, type: Int) {

        OSSUtils.newInstance(this)
            .putObjectMethod2(
                "userSetting/feedback",
                result[0].realPath,
                0,
                object : ProgressCallback2<PutObjectRequest, PutObjectResult> {
                    override fun onSuccess2(
                        request: PutObjectRequest?,
                        result: PutObjectResult?,
                        url: String?,
                        position: Int
                    ) {
                        if (type == 0) {
                            vm.getData012("id" to ids, "service_img" to url)
                        } else {
                            vm.getData012("id" to ids, "service_video" to url)
                        }

                    }

                    override fun onFailure(
                        request: PutObjectRequest?,
                        clientException: ClientException?,
                        serviceException: ServiceException?
                    ) {
                        ThreadUtils.runOnUiThread {
                            dismissLoading()
                            toast("图片上传失败")
                            Log.e("OSS onFailure！", "$clientException")
                            Log.e("OSS onFailure！", "$serviceException")
                        }
                    }

                    override fun onProgress(
                        request: PutObjectRequest?,
                        currentSize: Long,
                        totalSize: Long
                    ) {
                        //                                    Log.e("TAG", "图片上传: ${currentSize}/${totalSize}")
                    }
                })
    }

    private fun setUrl2(result2: ArrayList<LocalMedia>, type: Int) {
        var list88 = arrayListOf<String>()
        for (b in result2) {
            OSSUtils.newInstance(this)
                .putObjectMethod2(
                    "userSetting/feedback",
                    b.realPath,
                    0,
                    object : ProgressCallback2<PutObjectRequest, PutObjectResult> {
                        override fun onSuccess2(
                            request: PutObjectRequest?,
                            result: PutObjectResult?,
                            url: String?,
                            position: Int
                        ) {
                            list88.add(url!!)
                            if (list88.size == result2.size) {
                                var url2 = ""
                                for (b in list88) {
                                    url2 = url2 + b + ","
                                }
                                vm.getData012(
                                    "id" to ids,
                                    "service_img" to url2.subSequence(0, url2.length - 1)
                                )
                            }


                        }

                        override fun onFailure(
                            request: PutObjectRequest?,
                            clientException: ClientException?,
                            serviceException: ServiceException?
                        ) {
                            ThreadUtils.runOnUiThread {
                                dismissLoading()
                                toast("图片上传失败")
                                Log.e("OSS onFailure！", "$clientException")
                                Log.e("OSS onFailure！", "$serviceException")
                            }
                        }

                        override fun onProgress(
                            request: PutObjectRequest?,
                            currentSize: Long,
                            totalSize: Long
                        ) {
                            //                                    Log.e("TAG", "图片上传: ${currentSize}/${totalSize}")
                        }
                    })
        }

    }

    /**添加图片的抽象方法*/
    private fun addImage(
        context: Context,
        imageList: ArrayList<LocalMedia>,
        imageList2: ArrayList<LocalMedia>,
        adapter: ChooseImageAdapter2,
        s: String
    ) {
        if (s == "0") {
            PictureSelector.create(context)
                .openCamera(SelectMimeType.ofImage())
                .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                    override fun requestPermission(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?,
                        call: OnRequestPermissionListener?
                    ) {
                        permissionArray?.let {
                            PermissionHelper.requestPermission(
                                fragment?.context,
                                "权限说明",
                                "拍摄照片并上传",
                                *it
                            ) {
                                call?.onCall(permissionArray, it)
                            }
                        }
                    }

                    override fun hasPermissions(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?
                    ): Boolean {
                        return false
                    }
                })
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        if (result != null && result.size > 0) {
                            imageList2.addAll(result)
                            adapter.notifyDataSetChanged()
                            // toast("需要接口")
                            setUrl(result, 0)
                        }
                    }

                    override fun onCancel() {
                    }
                })
        } else {
            PictureSelector.create(context)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(9 - imageList.size) //图片最大选择数量
                .isDisplayCamera(false)  //是否显示相机入口
                .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                    override fun requestPermission(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?,
                        call: OnRequestPermissionListener?
                    ) {
                        permissionArray?.let {
                            PermissionHelper.requestPermission(
                                fragment?.context,
                                "权限说明",
                                "选择照片并上传",
                                *it
                            ) {
                                call?.onCall(permissionArray, it)
                            }
                        }
                    }

                    override fun hasPermissions(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?
                    ): Boolean {
                        return false
                    }
                })
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        if (result != null && result.size > 0) {
                            imageList2.addAll(result)
                            adapter.notifyDataSetChanged()
                            setUrl2(result, 0)
                        }
                    }

                    override fun onCancel() {
                    }
                })
        }

    }

    //图片添加事件
    private fun addInService() {
        startPageForResult<UploadInServiceActivity>("orderId" to ids.toString()){code, data ->
            if (code == 200) {
                vm.getData29("id" to ids)
            }
        }
        return
//        var listIamge = arrayListOf<LocalMedia>()
//        var listVideo = arrayListOf<LocalMedia>()
//        for (b in imageListInService) {
//            if (b.mimeType.contains("image")) {
//                listIamge.add(b)
//            } else {
//                listVideo.add(b)
//            }
//        }
//        if (listIamge.size < 9 && listVideo.size == 0) {
//            XPopup.Builder(this@ServiceOrderStatusActivity)
//
//                .asCustom(CheckDialog(this@ServiceOrderStatusActivity) {
//                    when (it) {
//                        "0" -> {
//                            XPopup.Builder(this@ServiceOrderStatusActivity)
//
//                                .asCustom(CheckDialog2(this@ServiceOrderStatusActivity) {
//                                    addImage(
//                                        this@ServiceOrderStatusActivity,
//                                        listIamge, imageListInService, inServiceAdapter, it
//                                    )
//                                })
//                                .show()
//
//                        }
//
//                        "1" -> {
//                            XPopup.Builder(this@ServiceOrderStatusActivity)
//
//                                .asCustom(CheckDialog2(this@ServiceOrderStatusActivity) {
//                                    addVideo(imageListInService, inServiceAdapter, it)
//                                })
//                                .show()
//
//                        }
//                    }
//                })
//                .show()
//        } else {
//            if (listVideo.size == 1) {
//                XPopup.Builder(this@ServiceOrderStatusActivity)
//
//                    .asCustom(CheckDialog2(this@ServiceOrderStatusActivity) {
//                        addImage(
//                            this@ServiceOrderStatusActivity,
//                            listIamge, imageListInService, inServiceAdapter, it
//                        )
//                    })
//                    .show()
//            } else {
//                XPopup.Builder(this@ServiceOrderStatusActivity)
//
//                    .asCustom(CheckDialog2(this@ServiceOrderStatusActivity) {
//                        addVideo(imageListInService, inServiceAdapter, it)
//                    })
//                    .show()
//
//            }
//
//        }


    }

    private fun addVideo(
        imageList2: ArrayList<LocalMedia>,
        adapter: ChooseImageAdapter2, s: String
    ) {
        if (s == "0") {
            PictureSelector.create(this@ServiceOrderStatusActivity)
                .openCamera(SelectMimeType.ofVideo())
                .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                    override fun requestPermission(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?,
                        call: OnRequestPermissionListener?
                    ) {
                        permissionArray?.let {
                            PermissionHelper.requestPermission(
                                fragment?.context,
                                "权限说明",
                                "录制视频并上传",
                                *it
                            ) {
                                call?.onCall(permissionArray, it)
                            }
                        }
                    }

                    override fun hasPermissions(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?
                    ): Boolean {
                        return false
                    }
                })
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        if (result != null && result.size > 0) {
                            imageList2.addAll(result)
                            adapter.notifyDataSetChanged()
                            setUrl(result, 1)
                        }
                    }

                    override fun onCancel() {
                    }
                })
        } else {
            PictureSelector.create(this@ServiceOrderStatusActivity)
                .openGallery(SelectMimeType.ofVideo())
                .setMaxSelectNum(1)
                .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                    override fun requestPermission(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?,
                        call: OnRequestPermissionListener?
                    ) {
                        permissionArray?.let {
                            PermissionHelper.requestPermission(
                                fragment?.context,
                                "权限说明",
                                "选择视频并上传",
                                *it
                            ) {
                                call?.onCall(permissionArray, it)
                            }
                        }
                    }

                    override fun hasPermissions(
                        fragment: Fragment?,
                        permissionArray: Array<out String>?
                    ): Boolean {
                        return false
                    }
                })
                .setImageEngine(GlideEngine.createGlideEngine())
                .isDisplayCamera(false)  //是否显示相机入口
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        if (result != null && result.size > 0) {
                            imageList2.addAll(result)
                            adapter.notifyDataSetChanged()
                            setUrl(result, 1)
                        }
                    }

                    override fun onCancel() {
                    }
                })
        }

    }

    var store_order_alarm_tel = ""
    var store_order_tel = ""


    var user_phone = ""
    var cate_id = ""
    var lat = ""
    var user_address = ""
    var lng = ""
    var gson = Gson()
    var listTime = arrayListOf<TimeBean8>()
    var list55 = arrayListOf<PriceBean>()
    var user_status = 0
    private fun getTime(date: Date): String {//可根据需要自行截取数据显示
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return format.format(date)
    }

    private fun millisecondsConvertToHMS(milliseconds: Long): String {
        val hoursStr: String
        val minutesStr: String
        val secondsStr: String

//时
        val hour = milliseconds / 1000 / 3600
        hoursStr = if (hour < 10) {
            "0$hour"
        } else {
            hour.toString() + ""
        }

//分
        val minute = milliseconds / 1000 % 3600 / 60
        minutesStr = if (minute < 10) {
            "0$minute"
        } else {
            minute.toString() + ""
        }

//秒
        val second = milliseconds / 1000 % 60
        secondsStr = if (second < 10) {
            "0$second"
        } else {
            second.toString() + ""
        }
        return "$hoursStr:$minutesStr:$secondsStr"
    }

    var str1 = ""
    var str2 = ""
    override fun startObserve() {
        // 付款成功
        LiveEventBus.get(ShouKuanPaySuccessEvent::class.java).observe(this) {
            binding.tvLeftButton3.gone()
        }
        LiveEventBus.get(TransferOrderSuccess::class.java).observe(this) {
            finish()
        }
        vm.getData012.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    toast("提交成功")
                }
            }
        }
        vm.getData29.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    list8.clear()

                    if (!it.before_service_img.isNullOrBlank()) {
                        var arr = it.before_service_img.split(",")
                        for (b in arr) {
                            list8.add(Image2Bean(b, 0))
                        }
                        if (!it.before_service_video.isNullOrBlank()) {
                            list8.add(Image2Bean(it.before_service_video, 1))
                        }
                    }
                    if (!it.service_img.isNullOrBlank()) {
                        var arr = it.service_img.split(",").filter { it.isNotEmpty() }
                        for (b in arr) {
                            var bean = LocalMedia()
                            bean.realPath = b
                            bean.mimeType = "image"
                            imageListInService.add(bean)
                        }
                    }
                    if (!it.service_video.isNullOrBlank()) {
                        var bean = LocalMedia()
                        bean.realPath = it.service_video
                        bean.mimeType = "video"
                        imageListInService.add(bean)
                    }
                    adapter8?.notifyDataSetChanged()
                    inServiceAdapter?.notifyDataSetChanged()
                }
            }
        }
        vm.getData222.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    if (it.finish_status == 0) {
                        startPage<OrderYsActivity>(
                            "finish_status" to it.finish_status,
                            "qrcode_url" to it.qrcode_url,
                            "orderId" to detailBean?.id.toString()
                        )
                    } else {
                        startPage<OrderYsActivity2>(
                            "finish_status" to it.finish_status,
                            "qrcode_url" to it.qrcode_url,
                            "orderId" to detailBean?.id.toString()
                        )
                    }

                }
            }
        }
        vm.getData6.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                XPopup.Builder(this@ServiceOrderStatusActivity)
                    .asCustom(
                        SmDialog(
                            this@ServiceOrderStatusActivity,
                            "您未到达用户下单地址 请到达用户下单地址在确认上门"
                        ) {

                        })
                    .show()
            }
            onSuccess {
                dismissLoading()
                binding.apply {
                    XPopup.Builder(this@ServiceOrderStatusActivity)
                        .asCustom(
                            SmDialog2(
                                this@ServiceOrderStatusActivity,
                                "上门地址:${it?.user_address}",
                                AccountUtils.user?.insurance_status == "1"
                            ) {
                                vm.confirmDoor(ids.toString())
                            })
                        .show()
                }
            }
        }
        // 确认上门
        vm.confirmDoorData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(2,10))
                LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
                startPageForResult<ComfirmDoorInActivity>(
                    "ids" to ids.toInt(),
                    "is_rework" to is_rework
                ) { code, data ->
                    if (code == 200) {
                        finish()
                    }
                }
            }
        }

        vm.getData55.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                if (it != null)
                    list55 = it
            }
        }
        vm.getData0.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                if (it !== null) {
                    try {
                        if (it.total_price.toDouble() > 0) {
                            var content = "当前订单有一笔额外费用客户未支付\n" +
                                    "请联系客户支付后在提交验收"
                            if (detailBean?.paid != 1) {
                                content =
                                    "当前订单有额外费用和订单金额客户\n未支付请联系客户支付后在提交验收"
                                XPopup.Builder(this@ServiceOrderStatusActivity)
                                    .asCustom(YsDialog(this@ServiceOrderStatusActivity, content) {
                                        startPage<ShouKuanActivity>(
                                            "team_id" to order_id.toString(),
                                            "serviceName" to detailBean?.store_name
                                        )
                                    })
                                    .show()
                            }else {
                                XPopup.Builder(this@ServiceOrderStatusActivity)
                                    .asCustom(YsDialog(this@ServiceOrderStatusActivity, content) {
                                        startPage<ExtraCostsPayActivity>(
                                            "orderId" to detailBean?.id.toString(),
                                            "payName" to "额外费用"
                                        )
                                    })
                                    .show()
                            }
                        } else {
                            if (detailBean?.paid != 1) {
                                val content =
                                    "当前订单有订单金额客户未支付\n请联系客户支付后在提交验收"
                                XPopup.Builder(this@ServiceOrderStatusActivity)
                                    .asCustom(YsDialog(this@ServiceOrderStatusActivity, content) {
                                        startPage<ShouKuanActivity>(
                                            "team_id" to order_id.toString(),
                                            "serviceName" to detailBean?.store_name
                                        )
                                    })
                                    .show()
                            } else {
                                startPageForResult<SubmitAcceptanceActivity>(
                                    "ids" to ids,
                                    "json" to json,
                                    "is_rework" to is_rework
                                ) { code, data ->
                                    if (code == 200) {
                                        setResult(200)
                                        finish()
                                    }
                                }
                            }
                        }
                    } catch (e: Exception) {

                    }

                }


            }
        }
        LiveEventBus.get("Sxx3", Boolean::class.java).observe(this) {
            finish()
        }

        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("修改成功")
                vm.getData("id" to ids)
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                //    toast(msg)
            }
            onSuccess {
                dismissLoading()
                listTime = it!!
                if (listTime.size > 0) {
                    // getTimeDate()
                    XPopup.Builder(this@ServiceOrderStatusActivity)
                        .asCustom(
                            TimelDialog(
                                this@ServiceOrderStatusActivity,
                                listTime
                            ) { service_day, service_time ->
                                vm.getData3(
                                    "order_id" to ids,
                                    "service_day" to service_day,
                                    "service_time" to service_time
                                )
                            })
                        .show()
                } else {
                    toast("没有可选择时间")
                }
            }
        }
        vm.getData22.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("提醒成功")
                AccountUtils.setReminderUserAcceptanceTime(it.toString())
            }
        }

        vm.getData66.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                XPopup.Builder(mActivity)
                    .asCustom(
                        SmDialog(
                            mActivity,
                            "您未到达用户下单地址 请到达用户下单地址在确认签到"
                        ) {

                        })
                    .show()
            }
            onSuccess {
                dismissLoading()
                XPopup.Builder(mActivity)
                    .asCustom(
                        SmDialog3(
                            mActivity,
                            "上门地址:${it?.user_address}",
                            detailBean?.insurance_status == "1"
                        ) {
                            // 打开确认签到页面
                            startPageForResult<MemberConfirmSignActivity>("order_id" to detailBean?.id.toString()) { code, data ->
                                if (code == 200) {
                                    // 签到成功
                                    LiveEventBus.get(SignSuccessEvent::class.java)
                                        .post(SignSuccessEvent(ids.toString()))
                                    binding.apply {
                                        vm.getData(
                                            "id" to ids, "lat" to lat9, "lng" to lng9
                                        )
                                    }
                                }
                            }
                        })
                    .show()
            }
        }

        vm.getData666.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                LiveEventBus.get(SignSuccessEvent::class.java)
                    .post(SignSuccessEvent(ids.toString()))
                binding.apply {
                    vm.getData(
                        "id" to ids, "lat" to lat9, "lng" to lng9
                    )
                }
            }
        }

        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                imageList.clear()
                detailBean = it

                if (it != null) {

                    // 重点区域
                    binding.tvKeyArea.text = "重点区域: ${it.key_areas}"
                    binding.tvKeyArea.visibleOrGone(!it.key_areas.isNullOrEmpty())


                    if (detailBean?.is_cart_order == 1) {

                        binding.recyclerViewSeriviceItem.visibility = View.VISIBLE
                        if (!detailBean?.order_goods.isNullOrEmpty()) {
                            binding?.tvServiceNum?.text =
                                "共" + detailBean?.order_goods?.size + "项服务明细"
                            var serviceItemAdapter = ServiceItemAdapter(detailBean?.order_goods!!)
                            binding.recyclerViewSeriviceItem.layoutManager = LinearLayoutManager(
                                this@ServiceOrderStatusActivity,
                                LinearLayoutManager.VERTICAL, false
                            )
                            binding.recyclerViewSeriviceItem.adapter = serviceItemAdapter
                        }
                        binding.storeName.visibility = View.GONE
                    } else {
                        binding.recyclerViewSeriviceItem.visibility = View.GONE
                        binding.storeName.visibility = View.VISIBLE
                    }


                    binding.tvTotalCount.text = "x${it.total_num}"
                    // 退款到账时间
                    binding.llReturnMoney.visibleOrGone(!it.refund_arrival_time.isNullOrEmpty())
                    binding.tvReturnMoney.text = it.refund_arrival_time

                    binding.llRewardView.visibleOrGone(0.0 != it.base_reward_amount?.toDoubleOrNull())
                    binding.tvRewardMoney.text = "${it.base_reward_amount}元"
                    try {
                        str1 = it.pay_price
                        binding.orderPrice.text = it.pay_price
                        if (it.is_hourly_worker == "0") {
                            binding.llKs4.gone()
                            // binding.llJe.gone()
                        } else {
                            binding.tvStartTime4.text = it.hourly_worker_end_time
                            binding.llKs4.visible()
                            //  binding.llJe.visible()

                            str2 = it.hourly_worker_cost

                        }

                    } catch (e: Exception) {

                    }

                    // 联系师傅
                    if (it.is_confirm == 1){
                        binding.tvContactWorker.visible()
                    }else{
                        binding.tvContactWorker.gone()
                    }

                    isqd = it.is_sign
                    order_id = it.order_id
                    if (it.is_confirm == 1 && it.user_status == 3) {
                        if (it.is_sign == 0) {
                            binding.tvRightButton2.gone()
                            binding.tvRightButton2.text = "立即签到"
                        } else {
                            binding.tvRightButton2.gone()
                            binding.tvRightButton2.text = "已签到"
                        }
                    } else {
                        binding.tvRightButton2.gone()
                    }
                    try {
                        binding.tvStartTime2.text = it.work_time
                        if (!it.confirm_service_time.isNullOrBlank()) {
                            binding.tvStartTime3.text = it.confirm_service_time
                            binding.tvStartTime3.visible()
                        } else {
                            binding.tvStartTime3.gone()
                        }

                    } catch (e: Exception) {
                    }
                    when (it.guarantee_status) {
                        "1" -> {
                            binding.ivSate.setImageResource(R.mipmap.dsx)
                        }

                        "2" -> {
                            binding.ivSate.setImageResource(R.mipmap.ysx)
                        }

                        else -> {
                            binding.ivSate.setImageResource(R.mipmap.ysx2)
                        }
                    }
                    //  0 ：待支付 1：待服务；2：服务中；3：已完成；4：已取消；5 待接单；6 验收中
                    user_status = it.user_status
                    if (it.status == "1") {
                        adapter =
                            ServiceOrderMemberListAdapter(
                                this@ServiceOrderStatusActivity,
                                imageList,
                                true,
                                ::add,
                                ::contact,
                                ::itemClick
                            )
                        /*  if ("已完成"==str||"已取消"==str){
                              adapter =
                                  ServiceOrderMemberListAdapter(
                                      this@ServiceOrderStatusActivity,
                                      imageList,
                                      false,
                                      ::add,
                                      ::contact,
                                      ::itemClick
                                  )
                          }else{
                              adapter =
                                  ServiceOrderMemberListAdapter(
                                      this@ServiceOrderStatusActivity,
                                      imageList,
                                      true,
                                      ::add,
                                      ::contact,
                                      ::itemClick
                                  )
                          }
*/
                    } else {
                        adapter =
                            ServiceOrderMemberListAdapter(
                                this@ServiceOrderStatusActivity,
                                imageList,
                                false,
                                ::add,
                                ::contact,
                                ::itemClick
                            )
                    }
                    binding.recyclerView.layoutManager =
                        GridLayoutManager(this@ServiceOrderStatusActivity, 6)
                    binding.recyclerView.adapter = adapter
                    try {
                        if (it.team_member.size > 0) {
                            binding.llRwd.visible()
                            binding.textView53.visible()
                            imageList.addAll(it.team_member!!)

                            adapter.notifyDataSetChanged()
                        } else {
                            binding.llRwd.gone()
                        }


                    } catch (e: Exception) {
                        binding.llRwd.gone()
                    }

                    binding.apply {
                        try {
                            if (it.confirm_door_time.isNullOrBlank()) {
                                llKs.gone()
                            } else {
                                tvStartTime.text = it.confirm_door_time
                                llKs.visible()
                            }
                        } catch (e: Exception) {

                        }
                        try {
                            if (it.cost_total.toDouble() > 0) {
                                tvPrice.text = "¥" + it.cost_total
                                tvPrice.clickWithTrigger {
                                    startPage<EwPriceActivity>("order_id" to ids)
                                }
                            } else {
                                tvPrice.text = "¥0"
                            }
                        } catch (e: Exception) {

                        }
                        try {
                            if (it.cost_list.size > 0) {
                                json = gson.toJson(it.cost_list)
                            }
                        } catch (e: Exception) {

                        }
                        if (it.is_need_pay == 0) {
                            tvLeftButton3.gone()
                        } else {
                            tvLeftButton3.visible()
                        }
                        is_team = it.is_team.toInt()
                        is_confirm = it.is_confirm
                        textView54.text = "服务质保期(${it.guarantee}天)"
                        var list88 = arrayListOf<Image2Bean>()
                        try {
                            for (b in it.images) {
                                if (!b.isNullOrBlank())
                                    list88.add(Image2Bean(b, 0))
                            }
                        } catch (e: Exception) {

                        }
                        try {
                            if (it.mark.isNullOrBlank()) {
                                if (list88.size > 0) {
                                    llBz.visible()
                                } else {
                                    llBz.gone()
                                }
                            } else {
                                tvMark.text = it.mark
                                llBz.visible()
                            }
                        } catch (e: Exception) {

                        }
                        try {
                            if (!it.video.isNullOrBlank()) {
                                list88.add(Image2Bean(it.video, 1))
                            }
                        } catch (e: Exception) {

                        }
                        list.clear()
                        list.addAll(list88)
                        imageadapter.notifyDataSetChanged()
                        when (AccountUtils.user?.insurance_status) {
                            "0" -> {
                                tvBz90.text = "未保障"
                            }

                            "1" -> {
                                tvBz90.text = "保障中"
                            }

                            "2" -> {
                                tvBz90.text = "已过期"
                            }
                        }
                        try {
                            if (user_status == 4) {
                                tvDj.text = "距您常用位置约${it.distance}km（仅供参考)"
                            } else {
                                tvDj.text =
                                    "距您门店位置${it.team_distance}km，距您常用位置约${it.distance}km（仅供参考)"
                            }

                        } catch (e: Exception) {

                        }
                        cate_id = it.cate_id
                        store_order_tel = it.store_order_tel
                        store_order_alarm_tel = it.store_order_alarm_tel
                        serviceTime.text = it.service_time
                        if (it.hourly_worker_time.isNullOrBlank()) {
                            storeName.text = "${it.store_name}"
                        } else {
                            if (it.hourly_worker_time == "0") {
                                storeName.text = "${it.store_name}"
                            } else {
                                storeName.text = "${it.store_name} [${it.hourly_worker_time}小时]"
                            }
                        }
                        // storeName.text=it.store_name
                        useAddress.text = it.base_address
                        realName.text = it.real_name
                        userPhone.text = it.user_phone
                        orderId.text = it.order_id
                        takeTime.text = it.add_order_time
                        imageView20.load(it.user_avatar, R.mipmap.my_toux)
                    }
                    cost_status = it.cost_select.toInt()
                    var num = 0.0
                    try {
                        num = it.confirm_door_timestamp as Double
                    } catch (e: Exception) {
                        Log.e("confirm_door_timestamp", num.toString())
                    }

                    try {
                        var time1 = num * 1000
                        if (time1 > 0) {
                            var countdown2 = (System.currentTimeMillis() - time1).toLong()
                            binding.textView53.visible()
                            countDownTimer?.cancel()
                            countDownTimer = null
                            countDownTimer =
                                object : CountDownTimer(10000000000000, 1 * 1000) {
                                    @SuppressLint("SimpleDateFormat")
                                    override fun onTick(millisUntilFinished: Long) {
                                        countdown2 = countdown2 + 1

                                        val s: String = formatDateTime(countdown2)
                                        //                Log.e("wy", "sysTimeStr s: "+s );
                                        binding.textView53.setText("服务时间:    ${s}")
                                    }

                                    override fun onFinish() {
                                        binding.textView53.setText("服务时间:   00:00:00")
                                        binding.textView53.gone()
                                    }
                                }
                            countDownTimer?.start()

                        }
                    } catch (e: Exception) {
                        Log.e("confirm_door_timestamp", num.toString())
                    }

                    var str = ""
                    when (it.status) {
                        "0" -> {

                            str = "待支付"

                        }

                        "1" -> {
                            if (it.is_confirm == 0) {
                                str = "待确认"
                            } else {
                                str = "待上门"

                            }
                        }

                        "2" -> {
                            str = "服务中"

                        }

                        "6" -> {
                            str = "验收中"


                        }

                        "5" -> {
                            str = "待接单"


                        }

                        "3" -> {
                            str = "已完成"
                        }
                        "10" -> {
                            str = "上门中"
                        }

                        else -> {
                            if (it.progress == 0) {
                                str = "已取消"

                            } else {
                                str = "退款中"

                            }
                        }

                    }
                    binding.appBar.tvTitle.text = str
                    //  0 ：待支付 1：待服务；2：服务中；3：已完成；4：已取消；5 待接单；6 验收中
                    when (it.status) {
                        "0" -> {
                            binding.llFw.gone()
                            binding.llBj2.gone()
                            binding.llKs2.gone()
                            binding.llKs3.gone()
                            if (it.is_team == "0") {//个人
                                //  binding.btB1.visible()
                            } else {//门店
                                when (it.user_status) {
                                    1 -> {
                                        //   binding.btB1.visible()
                                    }

                                    else -> {

                                        //   binding.btB1.gone()
                                    }
                                }
                            }
                            //待服务
                            //1团长2门店负责人3门店成员4普通用户


                            binding.llBj.gone()
                            if (it.is_team == "1") {
                                if (it.user_status == 1 || it.user_status == 2) {
                                    binding.imageView21.visible()
                                } else {
                                    binding.imageView21.gone()
                                }
                            } else {
                                binding.imageView21.visible()
                            }
                            //  binding.imageView21.visible()
                            binding.ivDw.visible()
                            binding.llKf.gone()
                            binding.btB2.gone()
                            binding.textView53.gone();
                            binding.btnSubmitAcceptance2.gone()
                            binding.llOrderProblem.gone()
                            binding.tvFw.gone()
                            binding.llEw.gone()
                            binding.tvComfirmDoorIn.gone()
                            binding.btnSubmitAcceptance.gone()
                            //  binding.appBar.tvTitle.text = "待支付"
                        }

                        "5" -> {
                            binding.llFw.gone()
                            binding.llBj2.gone()
                            binding.llKs2.gone()
                            binding.llKs3.gone()
                            //待服务
                            if (it.is_team == "1") {
                                if (it.user_status == 1 || it.user_status == 2) {
                                    binding.imageView21.visible()
                                } else {
                                    binding.imageView21.gone()
                                }
                            } else {
                                binding.imageView21.visible()
                            }
                            binding.ivDw.visible()
                            if (it.is_team == "0") {//个人
                                // binding.btB1.visible()
                            } else {//门店
                                when (it.user_status) {
                                    1 -> {
                                        //  binding.btB1.visible()
                                    }

                                    else -> {

                                        // binding.btB1.gone()
                                    }
                                }
                            }
                            binding.btB2.gone()
                            binding.llBj.gone()
                            binding.llKf.gone()
                            binding.btnSubmitAcceptance2.gone()
                            binding.llOrderProblem.gone()
                            binding.llEw.gone()
                            binding.textView53.gone();
                            binding.tvFw.gone()
                            binding.tvComfirmDoorIn.gone()
                            binding.btnSubmitAcceptance.gone()
                            //   binding.appBar.tvTitle.text = "待接单"
                        }

                        "1" -> {
                            var time90 = it.countdown.toString()
                            var isCs = it.is_overtime

                            if (it.is_confirm == 1) {
                                time90 = it.countdown.toString()
                                isCs = it.is_overtime
                                if (isCs == 0) {//正常
                                    binding.textView53.visible()
                                    if (time90.toLong() > 0) {
                                        countDownTimer?.cancel()
                                        countDownTimer = null
                                        countDownTimer =
                                            object : CountDownTimer(
                                                time90.toLong() * 1000,
                                                1 * 1000
                                            ) {
                                                @SuppressLint("SimpleDateFormat")
                                                override fun onTick(millisUntilFinished: Long) {
                                                    val s: String =
                                                        millisecondsConvertToHMS(millisUntilFinished)
                                                    //                Log.e("wy", "sysTimeStr s: "+s );
                                                    binding.textView53.setText("待确认:    " + s)
                                                }

                                                override fun onFinish() {
                                                    binding.textView53.gone()
                                                    /*  tvTime.setText("00:00:00")
                                                      item.is_overtime = 1
                                                      notifyItemChanged(holder.layoutPosition)*/
                                                }
                                            }
                                        countDownTimer?.start()
                                    } else {
                                        binding.textView53.gone()

                                    }
                                } else {
                                    binding.textView53.gone()
                                }
                            } else {
                                binding.textView53.gone()

                            }

                            binding.llFw.gone()
                            binding.llBj2.gone()
                            binding.llKs2.gone()
                            binding.llKs3.gone()
                            //待服务
                            if (it.is_team == "1") {
                                if (it.user_status == 1 || it.user_status == 2) {
                                    binding.imageView21.visible()
                                } else {
                                    binding.imageView21.gone()
                                }
                            } else {
                                binding.imageView21.visible()
                            }
                            binding.ivDw.visible()
                            binding.llOrderProblem.gone()
                            binding.btnSubmitAcceptance2.gone()
                            binding.llEw.gone()

                            binding.llBj.gone()
                            binding.llKf.gone()
                            //1团长2门店负责人3门店成员4普通用户
                            when (it.user_status) {
                                1 -> {
                                    // binding.btB1.visible()
                                    if (it.is_confirm == 0) {
                                        binding.btB2.visible()
                                        binding.tvComfirmDoorIn.visible()
                                        binding.tvComfirmDoorIn.text = "联系客户"
                                    } else {
                                        binding.btB2.gone()
                                        binding.tvComfirmDoorIn.visible()
                                        binding.tvComfirmDoorIn.text = "确认上门"

                                    }
                                }

                                2 -> {

                                    binding.btB2.gone()
                                    if (it.is_confirm == 0) {
                                        binding.tvComfirmDoorIn.visible()
                                        binding.btB1.gone()
                                        binding.tvComfirmDoorIn.text = "联系客户"
                                    } else {
                                        binding.btB1.gone()
                                        binding.tvComfirmDoorIn.visible()
                                        binding.tvComfirmDoorIn.text = "确认上门"

                                    }
                                }

                                4 -> {
                                    if (it.is_confirm == 0) {
                                        binding.tvComfirmDoorIn.visible()
                                        binding.btB1.gone()

                                        binding.tvComfirmDoorIn.text = "联系客户"
                                    } else {
                                        //   binding.btB1.visible()
                                        binding.tvComfirmDoorIn.visible()
                                        binding.tvComfirmDoorIn.text = "确认上门"
                                    }
                                    binding.btB2.gone()

                                }

                                else -> {
                                    binding.tvComfirmDoorIn.gone()
                                    binding.btB2.gone()
                                    binding.btB1.gone()
                                }
                            }

                            binding.btnSubmitAcceptance.gone()
                            binding.tvFw.gone()
                            //    binding.appBar.tvTitle.text = "待服务"
                        }

                        "10" -> {
                            // 上门中  点击进行确认上门
                            binding.tvConfirmedService.visible()
                            binding.textView53.gone()
                            // 服务日志 隐藏
                            binding.tvFw.gone()
                            // 订单遇到问题 隐藏
                            binding.llOrderProblem.gone()
                            // 开始时间 隐藏
                            binding.llKs.gone()
                            // 额外费用
                            binding.llEw.gone()
                            // 服务时长
                            binding.llKs2.gone()
                            // 完工时间
                            binding.llKs3.gone()
                            // 预计结束时间
                            binding.llKs4.gone()
                            // 退款到账时间
                            binding.llReturnMoney.gone()
                        }

                        "2" -> {
                            var num = 0.0
                            try {
                                num = it.confirm_door_timestamp.toDoubleOrNull() ?: 0.0
                            } catch (e: Exception) {
                                Log.e("confirm_door_timestamp", num.toString())
                            }


                            var time1 = num * 1000
                            if (time1 > 0) {
                                var countdown2 = (System.currentTimeMillis() - time1).toLong()
                                binding.textView53.visible()
                                countDownTimer?.cancel()
                                countDownTimer = null
                                countDownTimer =
                                    object : CountDownTimer(Int.MAX_VALUE.toLong(), 1 * 1000) {
                                        @SuppressLint("SimpleDateFormat")
                                        override fun onTick(millisUntilFinished: Long) {
                                            countdown2 = countdown2 + 1000

                                            val s: String = formatDateTime(countdown2)
                                            binding.textView53.setText("服务时间:    ${s}")
                                        }

                                        override fun onFinish() {
                                            binding.textView53.setText("服务时间:   00:00:00")
                                            binding.textView53.gone()
                                        }
                                    }
                                countDownTimer?.start()

                            }
                            //上门时间service_time
                            //结束时间bao_end_time

                            binding.llFw.visible()
                            binding.llBj.visible()
                            binding.llKf.visible()
                            binding.btB1.gone()
                            if (it.user_status == 3) {
                                binding.llOrderProblem.gone()
                                binding.llEw.gone()
                                binding.btnSubmitAcceptance.gone()
                            } else {
                                binding.llOrderProblem.gone()
                                binding.llEw.visible()
                                binding.btnSubmitAcceptance.visible()
                            }
                            binding.llOrderProblem.visible()
                            binding.btnSubmitAcceptance2.gone()

                            binding.btB2.gone()
                            binding.textView53.visible();
                            binding.tvFw.gone()
                            binding.tvComfirmDoorIn.gone()

                            //  binding.appBar.tvTitle.text = "服务中"
                            if (it.is_team == "1") {
                                if (it.user_status == 1 || it.user_status == 2) {
                                    binding.imageView21.visible()
                                } else {
                                    binding.imageView21.gone()
                                }
                            } else {
                                binding.imageView21.visible()
                            }
                            binding.ivDw.visible()
                            binding.llKs2.gone()
                            binding.llKs3.gone()
                            binding.llBj2.gone()
                        }

                        "3" -> {
                            binding.llFw.gone()
                            binding.llBj2.gone()
                            binding.llKs2.visible()
                            binding.tvContactWorker.gone()
                            binding.llKs3.visible()
                            binding.imageView21.gone()
                            binding.ivDw.gone()
                            binding.textView53.gone();
                            binding.llBj.gone()
                            binding.llKf.gone()
                            binding.btB1.gone()
                            binding.btB2.gone()
                            binding.btnSubmitAcceptance2.gone()
                            if (it.user_status == 3) {
                                binding.llEw.gone()
                            } else {
                                binding.llEw.visible()
                            }
                            binding.llOrderProblem.gone()
                            binding.tvFw.visible()
                            binding.tvComfirmDoorIn.gone()
                            binding.btnSubmitAcceptance.gone()
                            // binding.appBar.tvTitle.text = "已完成"

                        }

                        "6" -> {
                            binding.llKs2.visible()
                            binding.llBj2.visible()
                            binding.llKs3.visible()
                            binding.llFw.gone()
                            if (it.is_team == "1") {
                                if (it.user_status == 1 || it.user_status == 2) {
                                    binding.imageView21.visible()
                                } else {
                                    binding.imageView21.gone()
                                }
                            } else {
                                binding.imageView21.visible()
                            }
                            binding.ivDw.visible()
                            binding.textView53.gone();
                            binding.llBj.gone()
                            binding.llKf.visible()
                            binding.btB1.gone()
                            binding.btB2.gone()
                            binding.llOrderProblem.gone()
                            binding.btnSubmitAcceptance2.visible()
                            binding.llEw.visible()
                            binding.tvFw.gone()
                            binding.tvComfirmDoorIn.gone()
                            binding.btnSubmitAcceptance.gone()
                            //  binding.appBar.tvTitle.text = "验收中"

                        }

                        else -> {
                            binding.llKs2.gone()
                            binding.llBj2.gone()
                            binding.llKs3.gone()
                            binding.llFw.gone()
                            binding.imageView21.gone()
                            binding.ivDw.gone()
                            binding.textView53.gone();
                            binding.llBj.gone()
                            binding.llKf.gone()
                            binding.btB1.gone()
                            binding.btB2.gone()
                            binding.tvFw.gone()
                            binding.llOrderProblem.gone()

                            binding.llEw.gone()
                            binding.tvComfirmDoorIn.gone()
                            binding.btnSubmitAcceptance.gone()
                            if (it.progress == 0) {
                                binding.btnSubmitAcceptance22.gone()
                            } else {

                                if (it.is_overtime == 0) {

                                    if (it.define_second > 0) {
                                        binding.btnSubmitAcceptance22.visible()
                                    } else {
                                        binding.btnSubmitAcceptance22.gone()
                                    }
                                } else {
                                    binding.btnSubmitAcceptance22.gone()
                                }
                                binding.btnSubmitAcceptance22.gone()
                            }

                        }

                    }
                    user_phone = it.user_real_phone
                    user_address = it.user_address
                    if (lat != null) {
                        lat = it.lat
                        lng = it.lng
                    }

                    // 夜间服务费
                    val nighttime_amount = it.nighttime_amount?.toDoubleOrNull() ?: 0.0
                    binding.llNighttimeAmount.visibleOrGone(nighttime_amount > 0.0)
                    binding.tvNighttimeAmount.text = "${it.nighttime_amount}元"


                    if (it.hexiao_type=="2"){
                        binding?.layoutAddress?.visibility = View.GONE
                        binding?.tvTimeTitle?.text = "核销时间"
                        binding?.serviceTime?.text = it.finish_time
                        binding?.llEw?.visibility = View.GONE
                        binding?.llKs?.visibility = View.GONE
                        binding?.llKs2?.visibility = View.GONE
                        binding?.llKs3?.visibility = View.GONE
                        binding?.tvFw?.visibility = View.GONE
                    }else{
                        binding?.tvTimeTitle?.text = "期待上门时间"
                    }
                }

            }
        }
    }

    fun formatDateTime(milliseconds: Long): String {
        val sb = StringBuilder()
        val mss = milliseconds / 1000
        val days = mss / (60 * 60 * 24)
        val hours = mss % (60 * 60 * 24) / (60 * 60)
        val minutes = mss % (60 * 60) / 60
        val seconds = mss % 60
        val format = DecimalFormat("00")

        if (days > 0 || hours > 0) {
            sb.append(format.format(hours)).append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        } else {
            sb.append("00").append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        }
        return sb.toString()
    }

    /** 基础状态栏设置-蓝色背景，浅色字体*/
    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(false) //状态栏字体 true为深色 false为亮色
            statusBarColor(R.color.c_3b76c2)   //设置状态栏颜色
            titleBarMarginTop(binding.root)
        }
    }

}